package org.zn.etl.jdbc;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

public  abstract class Select extends Statment {
	
	protected  final static String SELECT="select";
	protected  final static String FROM="from";
	protected  final static String WHERE="where";
	
	protected  final static String ORDERBY="order by ";
	//条件表达式
	protected List<String> whereItems=new ArrayList<>();
	
	protected String  order;
	
	public void setOrder(String order) {
		this.order = order;
	}

	public void addWhere(String  relation,String column,String opt,String value) {
		whereItems.add(relation+SPACING+column+SPACING+opt+SPACING+value);
	}
	
	public String buildBaseSelect(){
	
		StringBuilder stb=new StringBuilder(SELECT);
		
		for (String col : columns) {
			stb.append(col).append(COMMA);
		}
		
		stb.replace(stb.length()-1, stb.length(), "");
		
		stb.append(SPACING).append(FROM);
		
		if(StringUtils.isNoneBlank(schema)) {
			stb.append(schema).append(DOT).append(tableName);
		}
		
		if(CollectionUtils.isNotEmpty(whereItems)) {
			stb.append(SPACING).append(WHERE).append(SPACING);
		
			for (int i = 0; i < whereItems.size(); i++) {
				
				if(i==0) {
				String[] frist=whereItems.get(i).split(SPACING);
				stb.append(frist[1]).append(frist[2]).append(frist[3]).append(SPACING);
				}else {
				stb.append(whereItems.get(i)).append(SPACING);	
				}

			}
			
		}
		
		if(StringUtils.isNotEmpty(order)) {
			stb.append(ORDERBY).append(SPACING).append(order);
		}
		
		return sql=stb.toString();
	}
	
	
	
	
	public String getSql() {
		return sql;
	}
	
	public abstract String getPageSelect() ;
	
}
